package com.czsth.sso.actions;

import com.czsth.sso.models.User;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

public class SSOAction extends ActionSupport implements ServletResponseAware, SessionAware {

    private String app;
    private String sessionId;
    private String source;

    private User user;
    private HttpServletResponse response;
    private Map<String, Object> session;

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    //跳转到登陆界面
    public String login_forward() {
        //这里可以获取传递过来的参数，需要很多的验证操作的，这里就省略了
        System.out.println("app->" + app);
        System.out.println("source->" + source);

        session.put("source", source);

        return SUCCESS;
    }


    public String login() throws IOException {

        HttpServletRequest request = ServletActionContext.getRequest();

        //这里简单的输出用户登陆信息，不做处理
        System.out.println(user.getUsername() + "-->" + user.getPassword());

        String ticket = System.currentTimeMillis() + "-" + new Random().nextInt();

        //登录成功后，重定向到原应用
        String url = (String) session.get("source");

        Cookie cookie = new Cookie("sso.ticket", ticket);
        cookie.setMaxAge(60 * 60 * 3);
        cookie.setHttpOnly(true);
//        cookie.setSecure(true);
        //这里有一个Cookie跨域的问题，这里暂时使用setPath的方式解决一下。
        cookie.setPath("/");

        //重定向回，用户最原始请求界面
        response.addCookie(cookie);
        response.sendRedirect(url);

        return NONE;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    public void setApp(String app) {
        this.app = app;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public void setSource(String source) {
        this.source = source;
    }
}
